import pandas as pd

'''
对心脏病数据进行单变量的描述分析
              多变量
'''

df = pd.read_csv('data/hd.csv')
# cp的频数
cp_value = df['cp'].value_counts()

'''
求频率
'''

# print(cp_value/cp_value.sum())
cp_counts = df['cp'].value_counts(normalize=True).round(4).to_list()
for i in cp_counts:
    print('%.2f' % (i * 100), '%')

'''
选取指定的列
'''

col = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']
df1 = pd.DataFrame(df, columns=col)
df2 = df.loc[:, ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']]
df3 = df[['age', 'trestbps', 'chol', 'thalach', 'oldpeak']]

''''
求和、平均数
'''
print(df1.count())
print(df1.sum())
print(df1.mean())

'''
中位数、众数和极小值
'''
print(df1.median())  # 中位数
print(df1.mode())  # 众数
print(df1.min())  # 极小值

'''
极大值和极小值所在的行的索引
'''
print(df1.idxmin())
print(df1.idxmax())

''''
空值和非空值
'''
print(df1.isna().sum())
'''
查看缺失比例
'''
print(df1.isna().mean())

'''
按照某一列的降序排序
'''
sort = df1.sort_values(['age', 'trestbps'], ascending=[True, False]).head()
print(sort)

'''
前四分之三
  四分之一
  标准差
  平方差
'''

print(df1.quantile(0.25))
print(df1.quantile(0.75))
print(df1.std())
print(df1.var())

'''
分组聚合
mode不能使用在分组之后
'''
group_age_mean = df1.groupby('age')['trestbps'].mean()
group_age_mean = df1.groupby('age')['trestbps'].median()

''''

'''
print(df1.describe())

''''
频数交叉表
'''
print(pd.crosstab(df.sex, df.num, margins=True))
'''
频率交叉表
'''
print(pd.crosstab(df.sex, df.num, margins=True, normalize=True).round(4))

'''
行轮廓交叉表
'''
print('***************************************')
print(pd.crosstab(df.sex, df.num, normalize=0))
print('***************************************')
print(pd.crosstab(df.sex, df.num, normalize='index'))
print('***************************************')
print(pd.crosstab(df.sex, df.num, normalize=1))  # 列

'''
分组
'''
df4 = df[['age', 'trestbps', 'chol', 'thalach', 'oldpeak','cp']]
print(df4.groupby('cp').mean())

print('**********************************************************')
''''
两两的相关性系数
'''
# 将子集类型全部转换
df1.astype('float64').dtypes
print(df1.corr().round(4))